package org.lhh.server.core.codec.steps;

import org.apache.commons.lang3.StringUtils;
import org.pentaho.di.core.exception.KettlePluginException;
import org.pentaho.di.partition.PartitionSchema;
import org.pentaho.di.trans.ModPartitioner;
import org.pentaho.di.trans.Partitioner;
import org.pentaho.di.trans.step.StepPartitioningMeta;

import java.util.HashMap;
import java.util.Map;

public class StepPartitioningMetaCodec {

    public static Map<String, String> encode(StepPartitioningMeta stepPartitioningMeta) {
        Map<String, String> map = new HashMap<>();
        map.put("method", stepPartitioningMeta.getMethodCode());
        PartitionSchema partitionSchema = stepPartitioningMeta.getPartitionSchema();
        map.put("schema_name", partitionSchema != null ? partitionSchema.getName() : "");
        Partitioner partitioner = stepPartitioningMeta.getPartitioner();
        if (partitioner != null) {
            if (partitioner instanceof ModPartitioner) {
                ModPartitioner modPartitioner = (ModPartitioner) partitioner;
                map.put("field_name", modPartitioner.getFieldName());
            }
        }
        return map;
    }

    public static StepPartitioningMeta decode(Map<String, String> map){
        StepPartitioningMeta stepPartitioningMeta = new StepPartitioningMeta();
        String method = map.get("method");
        if (StringUtils.isNotEmpty(method)) {
            try {
                stepPartitioningMeta.setMethod(method);
            } catch (KettlePluginException e) {

            }
        }
        stepPartitioningMeta.setPartitionSchemaName(map.get("schema_name"));
        Partitioner partitioner = stepPartitioningMeta.getPartitioner();
        if (partitioner != null) {
            if (partitioner instanceof ModPartitioner) {
                ModPartitioner modPartitioner = (ModPartitioner) partitioner;
                modPartitioner.setFieldName(map.get("field_name"));
            }
        }
        return stepPartitioningMeta;
    }
}
